/*
 * Copyright (C) 2008 GeoScheduler team, as stated on <http://www.geoscheduler.org/>.
 * 
 * This file is part of GeoScheduler.
 * 
 * GeoScheduler is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * GeoScheduler is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with GeoScheduler. If not, see <http://www.gnu.org/licenses/>.
 */
package org.geoscheduler.android.activities;

import org.geoscheduler.android.GSContext;
import org.geoscheduler.android.R;
import org.geoscheduler.android.exceptions.GSContextNotInitializedException;
import org.geoscheduler.android.exceptions.GSRestReturnedErrorException;
import org.geoscheduler.android.rest.Auth;
import org.geoscheduler.commons.msgs.types.AccountMsgs;
import org.geoscheduler.model.Account;
import org.geoscheduler.model.Token;
import org.geoscheduler.model.Account.AccountType;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;

/**
 * Google Account access development activity
 *
 * @author paja
 * @author srakyi
 */
public class Login extends Activity {
	private static final String LOGTAG = "LoginActivity";
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		
		setContentView(R.layout.login);

		/* This Context to be used in inner classes */
		final Context ctx = this;
		
		/* Initialize GSContext */
		GSContext.loadPrefs(ctx);
		
		/* Set stored values to form fields */
		try {
			Boolean prefRemember = (Boolean)GSContext.getPref(GSContext.PREFS_LP_REMEMBER);
			if ((prefRemember != null) && (prefRemember)) {
				((CheckBox)findViewById(R.id.login_remember)).setChecked(prefRemember);
				((EditText)findViewById(R.id.login_login)).setText((String)GSContext.getPref(GSContext.PREFS_LOGIN));
				((EditText)findViewById(R.id.login_passwd)).setText((String)GSContext.getPref(GSContext.PREFS_PASSWD));
			}
		} catch (GSContextNotInitializedException e1) {
			Log.e(LOGTAG, "Unexpected exception during activity initialization.", e1);
		}
		
		/* Initialize login button */
		ImageButton btn = (ImageButton) findViewById(R.id.login_button_login);
		btn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				Boolean remember = ((CheckBox)findViewById(R.id.login_remember)).isChecked();
				String login = ((EditText)findViewById(R.id.login_login)).getText().toString();
				String passwd = ((EditText)findViewById(R.id.login_passwd)).getText().toString();
				
				if (remember) {
					GSContext.putPref(GSContext.PREFS_LOGIN, login, ctx);
					GSContext.putPref(GSContext.PREFS_PASSWD, passwd, ctx);
					GSContext.putPref(GSContext.PREFS_LP_REMEMBER, remember, ctx);
				}
				
				// FIXME [srakyi] only GOOGLE_ACCOUNT type supported now
				Account acc = new Account(login, passwd, AccountType.GOOGLE_ACCOUNT);
				
				Auth auth = GSContext.getAuth();
				try {
					Token token = null;
					
					boolean registered = false;
					try {
						token = auth.logIn(acc);
					} catch (GSRestReturnedErrorException e) {
						// FIXME [srakyi] I don't like this way of handling errors :-/
						if (AccountMsgs.LOGIN_NOT_FOUND.name().equals(e.getMessage())) {
							auth.register(acc);
							registered = true;
							token = auth.logIn(acc);
						} else {
							throw e;
						}
					}
					
					
					if (token != null) {
						GSContext.setTokenAccount(token, acc);
//						showAlert(getString(R.string.label_info), 0, getString(R.string.login_msg_successful_reg_log_1) + (registered ? getString(R.string.login_msg_successful_reg_log_2) : "" )+ getString(R.string.login_msg_successful_reg_log_3), getString(R.string.label_ok), true);
						(new AlertDialog.Builder(Login.this)).
							setIcon(R.drawable.button_ok).
							setTitle(R.string.label_info).
							setMessage(R.string.login_msg_successful_reg_log_1).
							setPositiveButton(R.string.label_ok, null).
							create().
							show();
					} else {
//						showAlert(getString(R.string.label_error), 0, getString(R.string.login_msg_proper_token_not_returned), getString(R.string.label_ok), true);
						(new AlertDialog.Builder(Login.this)).
							setIcon(R.drawable.stop).
							setTitle(R.string.label_error).
							setMessage(R.string.login_msg_proper_token_not_returned).
							setPositiveButton(R.string.label_error, null).
							create().
							show();
					}
				} catch (GSRestReturnedErrorException e) {
//					showAlert(getString(R.string.label_error), 0, getString(R.string.msg_err_unexpected_error) + e.getMessage(), getString(R.string.label_ok), true);
					(new AlertDialog.Builder(Login.this)).
						setIcon(R.drawable.stop).
						setTitle(R.string.label_error).
						setMessage(R.string.msg_err_unexpected_error).
						setPositiveButton(R.string.label_error, null).
						create().
						show();
				} catch (Exception e) {
//					showAlert(getString(R.string.label_error), 0, getString(R.string.msg_err_unexpected_error) + e.getMessage(), getString(R.string.label_ok), true);
					(new AlertDialog.Builder(Login.this)).
						setIcon(R.drawable.stop).
						setTitle(R.string.label_error).
						setMessage(R.string.msg_err_unexpected_error).
						setPositiveButton(R.string.label_error, null).
						create().
						show();
					Log.e(LOGTAG, "Exception raised, during login attempt.", e);
				}
			}
		});
	}

}
